package com.cx.serializer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.util.Assert;

import java.nio.charset.Charset;

/**
 * 必须重写序列化器，否则@Cacheable注解的key会报类型转换错误
 *
 * @authors Alan
 */
public class StringRedisSerializer implements RedisSerializer<Object> {
 
    private final Charset charset;
 
    private final String target = "\"";
 
    private final String replacement = "";
 
    public StringRedisSerializer() {
        this(Charset.forName("UTF8"));
    }
 
    public StringRedisSerializer(Charset charset) {
        Assert.notNull(charset, "Charset must not be null!");
        this.charset = charset;
    }
 
    @Override
    public String deserialize(byte[] bytes) {
        return (bytes == null ? null : new String(bytes, charset));
    }

    @Override
    public byte[] serialize(final Object object) {
        if (object == null) {
            return null;
        }
        String string;
        if(!(object instanceof String)){
            string = JSON.toJSONString(object, SerializerFeature.WriteMapNullValue);
            if (StringUtils.isBlank(string)) {
                return null;
            }
            string = trimFirstAndLastChar(string, target);
        }else {
            string = (String)object;
        }

        return string.getBytes(charset);
    }

    //去掉首尾指定字符串
    private String trimFirstAndLastChar(String source, String element){

        source = source.replaceFirst(element, replacement);
        source = source.substring(0, source.lastIndexOf(element) -1);
        return source;

    }
}